<?php

namespace App\Console\Commands;

use App\Models\AgentRechargeRecord;
use App\Models\Order;
use App\Models\OrderReadInfo;
use App\Models\Setting;
use App\Notifications\CommonMessage;
use App\Service\WxArticleData;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Notification;

class GetOrderReadInfo extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'get:order_read_info';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '更新订单阅读数据';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $date = Carbon::now()->toDateString();
        $hour = Carbon::now()->hour;
        $min = intval(Carbon::now()->minute / 5);
        $order_off_rate = json_decode(Setting::query()->firstOrCreate(['key' => 'order_off_rate'], ['value' => null])->value);

        Order::query()->where('state', Order::ORDER_STATE_ON)->get()->each(function ($order) use ($date, $hour, $min, $order_off_rate) {
            $read_info = WxArticleData::get($order->url);
            if ($read_info && $read_info->code == 200) {
                $read_num_inc = $read_info->read_num - $order->current_read_num;
                $order->current_read_num = $read_info->read_num;
                $order->save();//更新订单阅读数据
                OrderReadInfo::query()->updateOrCreate([
                    'order_id' => $order->id,
                    'hour' => $hour,
                    'min_area' => $min,
                    'date' => $date,
                ], [
                    'read_num_inc' => $read_num_inc,
                    'amount' => ($read_num_inc / 1000) * $order->cpm
                ]);
            }
            //检查订单进度，是否自动关闭
            $com_rate = (($order->current_read_num - $order->initialization_read_num) / ($order->expect_read_num - $order->initialization_read_num));
            if ($com_rate > ($order_off_rate / 100)) {

                //达到订单自动关闭条件

                try {
                    DB::beginTransaction();

                    //计算订单消耗

                    $amount = (($order->expect_read_num - $order->current_read_num) / 1000) * $order->cpm;

                    //记录日志
                    $agent = $order->adminUser->agent;
                    AgentRechargeRecord::query()->create([
                        'admin_user_id' => $order->admin_user_id,
                        'operator' => 'sys',
                        'amount' => $amount,
                        'balance' => $agent->balance + $amount,
                        'remark' => '订单完成度：' . $com_rate . '，自动关闭订单，余额已退回'
                    ]);
                    $agent->increment('balance', $amount);//退款
                    $order->state = Order::ORDER_STATE_OFF;//修改订单状态为关闭
                    $order->stopped_at = Carbon::now()->toDateTimeString();//修改订单结束时间
                    $order->save();
                    DB::commit();
                    $count = Order::query()->where('state', Order::ORDER_STATE_ON)->count();
                    Notification::send(new \stdClass(),
                        new CommonMessage('订单【' . $order->name. '】完成度【'.$com_rate.'】,已经被系统自动关闭，当前系统实时在投订单：' . $count . '个')
                    );
                    //通知代理
                    if( $agent->qywx != null){
                        //设置代理企业微信，通知代理
                        $agent_count = Order::query()->where([
                            'state'=> Order::ORDER_STATE_ON,
                            'admin_user_id' => $agent->admin_user_id
                        ])->count();
                        Notification::send(new \stdClass(),
                            new CommonMessage('您的订单【' . $order->name . '】完成度【' . (round($com_rate,2) *100). '%】,已经被系统自动关闭，订单余额：'.$amount.'已退回，您的实时在投订单剩余：' . $agent_count . '个', $agent->qywx)
                        );
                    }

                } catch (\Exception $exception) {
                    DB::rollBack();
                    Log::error('自动关闭订单错误：' . $exception->getMessage());

                }

            }


        });
    }
}
